package cn.com.taiji.pos.config;

import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.pos.entity.SystemAclUser;
import cn.com.taiji.pos.service.IConfigBusinessTypeService;
import cn.com.taiji.pos.service.ISystemAclUserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Map;

@Aspect
@Component
public class LoggerAspect {

    @Autowired
    private ISystemAclUserService systemAclUserService;
    @Autowired
    private IConfigBusinessTypeService configBusinessTypeService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 定义切点Pointcut
    @Pointcut("execution(* cn.com.taiji.pos.controller..*.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public synchronized Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request;
        request = sra.getRequest();
        SystemAclUser user = (SystemAclUser) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        if (user == null && request.getHeader("userId") != null) {
            user = systemAclUserService.getById(request.getHeader("userId"));
            WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, user);
        }
        System.out.println();
        System.out.println("请求开始===地址:" + request.getServletPath());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("请求开始===时间:" + df.format(LocalDateTime.now()));
        String method = request.getMethod();
        String queryString = request.getQueryString();
        Map<String, String[]> parameterMap = request.getParameterMap();
        Object[] args = pjp.getArgs();
        //获取请求参数集合并进行遍历拼接
        if (args.length > 0) {
            if ("POST".equals(method)) {
                if (args.length > 2 & parameterMap.size() < 1) {
                    //requestBody参数
                    getKeyAndValue(args[0]);
                } else if (parameterMap.size() > 0) {
                    //requestParam参数
                    printParams(parameterMap);
                }
            } else if ("GET".equals(method)) {
                if (queryString != null && !"".equals(queryString)) {
                    for (String param : queryString.split("&")) {
                        if (StringUtils.hasText(param.split("=")[1])) {
                            System.out.println("接收到参数" + param.split("=")[0] + "的值为:" + param.split("=")[1]);
                        }
                    }
                }
            }
        }
        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
//        System.out.println("请求结束");
        return result;
    }

    private static void getKeyAndValue(Object obj) {
        // 得到类对象
        Class userCla = obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            f.setAccessible(true); // 设置些属性是可以访问的
            Object val;
            try {
                val = f.get(obj);
                // 得到此属性的值
                if (val != null && !"serialVersionUID".equals(f.getName()) && !"DEFAULT_INITIAL_CAPACITY".equals(f.getName())) {
                    System.out.println("接收到参数" + f.getName() + "的值为:" + val);
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    private static void printParams(Map<String, String[]> obj) {
        for (String key : obj.keySet()) {
            System.out.println("接收到参数" + key + "的值为:" + Arrays.toString(obj.get(key)));
        }
    }


}
